#!/usr/bin/env node
const readline = require("readline");
const net = require("net");

// 终端颜色
const colors = {
    reset: "\x1b[0m",
    green: "\x1b[32m",
    red: "\x1b[31m",
    yellow: "\x1b[33m",
    cyan: "\x1b[36m",
    magenta: "\x1b[35m",
    blue: "\x1b[34m",
    white: "\x1b[37m",
    brightRed: "\x1b[91m",
    brightGreen: "\x1b[92m",
    brightYellow: "\x1b[93m",
    brightBlue: "\x1b[94m",
    brightMagenta: "\x1b[95m",
    brightCyan: "\x1b[96m",
    gray: "\x1b[90m",
};

// 玩家颜色配置
const playerColors = [
    colors.brightGreen,   // 玩家1 - 亮绿色
    colors.brightBlue,    // 玩家2 - 亮蓝色  
    colors.brightYellow,  // 玩家3 - 亮黄色
    colors.brightMagenta, // 玩家4 - 亮紫色
    colors.brightCyan,    // 玩家5 - 亮青色
    colors.brightRed,     // 玩家6 - 亮红色
    colors.white,         // 玩家7 - 白色
    colors.cyan,          // 玩家8 - 青色
];

// 游戏参数
const GROUND_Y = 20;
const GAME_WIDTH = 120;
const GAME_HEIGHT = 24;
const JUMP_HEIGHT = 9;
const GRAVITY = 0.3;
const INITIAL_SPEED = 12;
const MAX_SPEED = 30;

// 恐龙状态
const DinoState = {
    RUNNING: 'running',
    JUMPING: 'jumping',
    DEAD: 'dead',
    WAITING: 'waiting'
};

// 障碍物类型
const ObstacleType = {
    CACTUS_SMALL: {
        width: 3, 
        height: 3, 
        points: 1,
        draw: [
            [' ', '█', ' '],
            ['█', '█', '█'],
            [' ', '█', ' ']
        ]
    },
    CACTUS_LARGE: {
        width: 5, 
        height: 5, 
        points: 2,
        draw: [
            [' ', ' ', '█', ' ', ' '],
            [' ', '█', '█', '█', ' '],
            ['█', '█', '█', '█', '█'],
            [' ', ' ', '█', ' ', ' '],
            [' ', ' ', '█', ' ', ' ']
        ]
    },
};

const CLOUD_ART = [
    [' ', '_', '_', ' '],
    ['(', '_', '_', ')']
];

// 游戏状态
let gameMode = "single";
let gameState = "menu";
let gameSpeed = INITIAL_SPEED;
let gameDistance = 0;
let groundOffset = 0;
let obstacles = [];
let clouds = [];
let players = new Map();
let currentPlayerId = "player1";
let server = null;
let client = null;
let gameLoop = null;
let lastUpdate = Date.now();
const serverUpdateInterval = 50;
let isServer = false;
let isClient = false;

// 玩家类
class Dino {
    constructor(id, x = 5, color = colors.brightGreen) {
        this.id = id;
        this.x = x;
        this.y = GROUND_Y;
        this.velocityY = 0;
        this.state = DinoState.WAITING;
        this.score = 0;
        this.color = color;
        this.alive = true;
    }

    jump() {
        if (this.state === DinoState.RUNNING && this.alive) {
            this.state = DinoState.JUMPING;
            this.velocityY = -Math.sqrt(2 * GRAVITY * JUMP_HEIGHT);
        }
    }

    update() {
        if (!this.alive) return;
        if (this.state === DinoState.JUMPING) {
            this.velocityY += GRAVITY;
            this.y += this.velocityY;
            if (this.y >= GROUND_Y) {
                this.y = GROUND_Y;
                this.velocityY = 0;
                this.state = DinoState.RUNNING;
            }
        }
    }

    checkCollision(obstacle) {
        if (!this.alive) return false;
        const dinoHeight = 7, dinoWidth = 7, margin = 1;
        const dinoLeft = this.x + margin, dinoRight = this.x + dinoWidth - margin;
        const dinoTop = this.y - dinoHeight + margin, dinoBottom = this.y - margin;
        const obstacleBaseY = obstacle.type.y || GROUND_Y;
        const obstacleTop = obstacleBaseY - obstacle.type.height + 1, obstacleBottom = obstacleBaseY;
        const obstacleLeft = obstacle.x, obstacleRight = obstacle.x + obstacle.type.width;
        return !(dinoRight < obstacleLeft || dinoLeft > obstacleRight || dinoBottom < obstacleTop || dinoTop > obstacleBottom);
    }

    die() {
        this.alive = false;
        this.state = DinoState.DEAD;
    }

    reset() {
        this.y = GROUND_Y;
        this.velocityY = 0;
        this.state = DinoState.WAITING;
        this.score = 0;
        this.alive = true;
    }
}

// 障碍物类
class Obstacle {
    constructor(x, type) {
        this.x = x;
        this.type = type;
        this.passedByPlayers = new Set(); // 记录哪些玩家已经通过
    }
    update(speed) { this.x -= speed / 6; }
    
    hasPlayerPassed(playerId) {
        return this.passedByPlayers.has(playerId);
    }
    
    markPlayerPassed(playerId) {
        this.passedByPlayers.add(playerId);
    }
}

// 云彩类
class Cloud {
    constructor(x, y, art) {
        this.x = x;
        this.y = y;
        this.art = art;
    }
    update(speed) { this.x -= speed / 20; }
}

// 网络功能
function createServer(port = 3000) {
    server = net.createServer(socket => {
        const connectionId = players.size;
        const playerId = `player${connectionId + 1}`;
        const playerColor = playerColors[connectionId % playerColors.length];
        socket.setNoDelay(true);
        const startX = 5 + (connectionId + 1) * 10; // 从服务器玩家后开始，间距统一为10
        const dino = new Dino(playerId, startX, playerColor);
        players.set(playerId, { socket, dino, connected: true, ready: false });
        console.log(`${colors.green}玩家 ${playerId} 已连接${colors.reset}`);
        socket.on('data', data => {
            try {
                const messages = data.toString().split('}{').map((msg, i, arr) => {
                    if (i === 0 && arr.length > 1) return msg + '}';
                    if (i === arr.length - 1 && arr.length > 1) return '{' + msg;
                    if (arr.length > 1) return '{' + msg + '}';
                    return msg;
                });
                messages.forEach(msgStr => {
                    if (msgStr.trim()) {
                        const message = JSON.parse(msgStr);
                        handleClientMessage(playerId, message);
                    }
                });
            } catch (e) {}
        });
        socket.on('close', () => {
            console.log(`${colors.red}玩家 ${playerId} 已断开${colors.reset}`);
            if (players.has(playerId)) players.get(playerId).connected = false;
            broadcastPlayerList();
        });
        sendToClient(socket, { type: 'connected', playerId, color: playerColor, x: startX });
        broadcastPlayerList();
    }).listen(port, () => {
        console.log(`${colors.cyan}服务器启动在端口 ${port}${colors.reset}`);
        isServer = true;
        gameMode = "server";
        // 服务器玩家在最左边，客户端玩家从右边开始
        const serverDino = new Dino('server', 5, playerColors[0]);
        players.set('server', { dino: serverDino, connected: true, ready: false, isServer: true });
    });
}

function connectToServer(host = 'localhost', port = 3000) {
    client = net.createConnection(port, host, () => {
        console.log(`${colors.green}已连接到服务器${colors.reset}`);
        isClient = true;
        gameMode = "client";
        gameState = "waiting";
    });
    client.setNoDelay(true);
    client.on('data', data => {
        try {
            const messages = data.toString().split('}{').map((msg, i, arr) => {
                if (i === 0 && arr.length > 1) return msg + '}';
                if (i === arr.length - 1 && arr.length > 1) return '{' + msg;
                if (arr.length > 1) return '{' + msg + '}';
                return msg;
            });
            messages.forEach(msgStr => {
                if(msgStr) handleServerMessage(JSON.parse(msgStr));
            });
        } catch (e) {}
    });
    client.on('close', () => {
        console.log(`${colors.red}与服务器连接已断开${colors.reset}`);
        process.exit();
    });
}

function sendToClient(socket, message) {
    if (socket && !socket.destroyed) socket.write(JSON.stringify(message));
}

function sendToServer(message) {
    if (client && !client.destroyed) client.write(JSON.stringify(message));
}

function broadcastMessage(message) {
    if (!isServer) return;
    players.forEach(player => {
        if (player.socket && player.connected) sendToClient(player.socket, message);
    });
}

function broadcastPlayerList() {
    if (!isServer) return;
    const playerList = Array.from(players.values())
        .filter(p => p.connected)
        .map(p => ({ 
            id: p.dino.id, 
            ready: p.ready, 
            color: p.dino.color, 
            x: p.dino.x,
            y: p.dino.y,
            state: p.dino.state,
            alive: p.dino.alive,
            score: p.dino.score
        }));
    broadcastMessage({ type: 'playerList', players: playerList });
}

function broadcastGameState() {
    if (!isServer) return;
    const playerStates = Array.from(players.values())
        .filter(p => p.connected)
        .map(p => ({
            id: p.dino.id,
            x: p.dino.x,
            y: p.dino.y,
            state: p.dino.state,
            score: p.dino.score,
            alive: p.dino.alive,
            color: p.dino.color
        }));
    
    broadcastMessage({
        type: 'gameState',
        state: gameState,
        speed: gameSpeed,
        distance: gameDistance,
        obstacles: obstacles.map(o => ({ 
            x: o.x, 
            type: o.type, 
            passedByPlayers: Array.from(o.passedByPlayers)
        })),
        players: playerStates
    });
}

function handleClientMessage(playerId, message) {
    const player = players.get(playerId);
    if (!player) return;
    switch (message.type) {
        case 'ready':
            player.ready = true;
            console.log(`${colors.yellow}玩家 ${playerId} 已准备${colors.reset}`);
            broadcastPlayerList();
            checkAllReady();
            break;
        case 'jump':
            if (player.dino && gameState === 'playing') player.dino.jump();
            break;
        case 'restart':
            if (gameState === 'gameover') requestRestart(playerId);
            break;
    }
}

function handleServerMessage(message) {
    switch (message.type) {
        case 'connected':
            currentPlayerId = message.playerId;
            players.set(message.playerId, { dino: new Dino(message.playerId, message.x, message.color), connected: true, ready: false });
            console.log(`${colors.cyan}你是 ${message.playerId}${colors.reset}`);
            break;
        case 'playerList':
            updatePlayerList(message.players);
            break;
        case 'gameStart':
            startGame();
            break;
        case 'gameState':
            updateGameState(message);
            break;
        case 'gameOver':
            handleGameOver(message);
            break;
        case 'returnToLobby':
            gameState = 'waiting';
            break;
    }
}

function updatePlayerList(playerList) {
    const updatedPlayers = new Map();
    playerList.forEach(p => {
        let existing = players.get(p.id);
        if (existing) {
            // 更新现有玩家信息
            existing.ready = p.ready;
            existing.connected = true;
            existing.dino.x = p.x;
            existing.dino.y = p.y;
            existing.dino.state = p.state;
            existing.dino.alive = p.alive;
            existing.dino.color = p.color;
            // 添加分数同步
            if (p.score !== undefined) {
                existing.dino.score = p.score;
            }
            updatedPlayers.set(p.id, existing);
        } else {
            // 创建新玩家
            const newDino = new Dino(p.id, p.x, p.color);
            newDino.y = p.y;
            newDino.state = p.state;
            newDino.alive = p.alive;
            newDino.score = p.score || 0;
            updatedPlayers.set(p.id, { 
                dino: newDino, 
                connected: true, 
                ready: p.ready 
            });
        }
    });
    players = updatedPlayers;
}

function updateGameState(message) {
    gameState = message.state;
    gameSpeed = message.speed;
    gameDistance = message.distance;
    obstacles = message.obstacles.map(o => {
        const obstacle = new Obstacle(o.x, o.type);
        if (o.passedByPlayers) {
            obstacle.passedByPlayers = new Set(o.passedByPlayers);
        }
        return obstacle;
    });
    message.players.forEach(p => {
        let player = players.get(p.id);
        if (player) {
            player.dino.y = p.y;
            player.dino.state = p.state;
            player.dino.score = p.score;
            player.dino.alive = p.alive;
        }
    });
}

function checkAllReady() {
    if (!isServer) return;
    const connectedPlayers = Array.from(players.values()).filter(p => p.connected);
    if (connectedPlayers.length > 0 && connectedPlayers.every(p => p.ready)) {
        console.log(`${colors.green}所有玩家已准备，游戏即将开始！${colors.reset}`);
        setTimeout(() => {
            broadcastMessage({ type: 'gameStart' });
            startGame();
        }, 1000);
    }
}

function requestRestart(playerId) {
    if (!isServer) return;
    console.log(`${colors.yellow}${playerId} 请求重新开始${colors.reset}`);
    
    // 清理游戏循环
    if (gameLoop) {
        clearInterval(gameLoop);
        gameLoop = null;
    }
    
    // 重置所有玩家状态
    players.forEach(player => {
        if (player.connected) {
            player.ready = false;
            player.dino.reset();
        }
    });
    
    // 重置游戏状态
    gameState = 'waiting';
    gameSpeed = INITIAL_SPEED;
    gameDistance = 0;
    groundOffset = 0;
    obstacles = [];
    clouds = [];
    lastUpdate = Date.now();
    
    // 通知所有客户端返回大厅
    broadcastMessage({ type: 'returnToLobby' });
    broadcastPlayerList();
}

// 游戏逻辑
function startGame() {
    gameState = 'playing';
    gameSpeed = INITIAL_SPEED;
    gameDistance = 0;
    groundOffset = 0;
    obstacles = [];
    clouds = [];
    players.forEach(player => {
        if (player.connected) {
            player.dino.state = DinoState.RUNNING;
            player.dino.alive = true;
            player.dino.score = 0;
        }
    });
    lastUpdate = Date.now();
    if (gameLoop) clearInterval(gameLoop);
    gameLoop = setInterval(updateGame, serverUpdateInterval);
}

function updateGame() {
    if (gameState !== 'playing') return;
    const now = Date.now();
    const deltaTime = (now - lastUpdate) / 1000;
    lastUpdate = now;

    // 使用平滑曲线增加速度 (指数衰减曲线)
    const timeProgress = gameDistance / 1000; // 时间进度因子
    const speedCurve = 1 - Math.exp(-timeProgress * 0.3); // 指数衰减曲线
    gameSpeed = INITIAL_SPEED + (MAX_SPEED - INITIAL_SPEED) * speedCurve;
    gameDistance += gameSpeed * deltaTime * 5;

    // 动态障碍物生成概率 (更平衡的增长曲线)
    const obstacleTimeProgress = gameDistance / 1500; // 缩短达到最大难度的距离
    const obstacleCurve = 1 / (1 + Math.exp(-3 * (obstacleTimeProgress - 0.8))); // 调整S曲线参数
    const baseProb = 0.035 + 0.045 * obstacleCurve; // 从3.5%增长到8%，提高初始概率
    
    // 动态最小间距 (保持合理间距，避免高分时过于密集)
    const gapCurve = Math.exp(-timeProgress * 0.08); // 进一步降低衰减速度
    const minGap = Math.max(50, 85 * gapCurve + Math.random() * 15); // 提高最小和最大间距
    
    if (Math.random() < baseProb && (obstacles.length === 0 || obstacles[obstacles.length - 1].x < GAME_WIDTH - minGap)) {
        const types = [ObstacleType.CACTUS_SMALL, ObstacleType.CACTUS_LARGE];
        obstacles.push(new Obstacle(GAME_WIDTH, types[Math.floor(Math.random() * types.length)]));
    }

    obstacles.forEach(o => o.update(gameSpeed));
    obstacles = obstacles.filter(o => o.x > -10);
    
    // 更新地形偏移量，与障碍物同步移动
    groundOffset += gameSpeed / 6;

    if (Math.random() < 0.02 && clouds.length < 7) {
        clouds.push(new Cloud(GAME_WIDTH, Math.floor(Math.random() * (GROUND_Y - 15)) + 2, CLOUD_ART));
    }
    clouds.forEach(c => c.update(gameSpeed));
    clouds = clouds.filter(c => c.x > -20);

    let aliveCount = 0;
    players.forEach(player => {
        if (player.connected && player.dino.alive) {
            player.dino.update();
            obstacles.forEach(obstacle => {
                if (player.dino.checkCollision(obstacle)) {
                    player.dino.die();
                } else if (!obstacle.hasPlayerPassed(player.dino.id) && obstacle.x < player.dino.x) {
                    player.dino.score += obstacle.type.points;
                    obstacle.markPlayerPassed(player.dino.id);
                }
            });
            if (player.dino.alive) aliveCount++;
        }
    });

    if (isServer && Array.from(players.values()).filter(p => p.connected).every(p => !p.dino.alive)) {
        endGame();
    } else if (gameMode === 'single' && !players.get('player1').dino.alive) {
        endGame();
    }

    if (isServer) broadcastGameState();
    if (gameMode === 'single' || isServer) render();
}

function endGame() {
    gameState = 'gameover';
    if (gameLoop) clearInterval(gameLoop);
    const rankings = Array.from(players.values())
        .filter(p => p.connected)
        .map(p => ({ id: p.dino.id, score: p.dino.score, color: p.dino.color }))
        .sort((a, b) => b.score - a.score);
    if (isServer) broadcastMessage({ type: 'gameOver', rankings });
    showGameOver(rankings);
}

function handleGameOver(message) {
    gameState = 'gameover';
    if (gameLoop) clearInterval(gameLoop);
    showGameOver(message.rankings);
}

function showGameOver(rankings) {
    renderGameWorld();
    console.log(`\n${colors.red}${'='.repeat(40)}${colors.reset}`);
    console.log(`${colors.yellow}          游戏结束！${colors.reset}`);
    console.log(`${colors.red}${'='.repeat(40)}${colors.reset}\n`);
    console.log(`${colors.cyan}最终排名：${colors.reset}\n`);
    rankings.forEach((player, index) => {
        const medal = ['🥇', '🥈', '🥉'][index] || `${index + 1}.`;
        console.log(`${medal} ${player.color}${player.id}${colors.reset} - ${colors.yellow}${player.score} 分${colors.reset}`);
    });
    console.log(`\n${colors.gray}按 R 键重新开始，按 Ctrl+C 退出${colors.reset}`);
}

// 渲染
function clearScreen() { console.clear(); }

function render() {
    if (gameState === 'waiting') renderWaitingLobby();
    else if (gameState === 'playing' || gameState === 'gameover') renderGameWorld();
}

function renderWaitingLobby() {
    clearScreen();
    const screen = Array.from({ length: GAME_HEIGHT }, () => Array(GAME_WIDTH).fill(' '));
    const title = "=== 等待玩家准备 ===", instructions = "按 [空格] 准备 | 按 [Ctrl+C] 退出";
    screen[2].splice(Math.floor(GAME_WIDTH / 2 - title.length / 2), title.length, ...title.split(''));
    screen[4].splice(Math.floor(GAME_WIDTH / 2 - instructions.length / 2), instructions.length, ...instructions.split(''));
    for (let x = 0; x < GAME_WIDTH; x++) screen[GROUND_Y + 1][x] = colors.gray + '▔' + colors.reset;
    
    const dinoArt = { idle: ["    ▄▄ ", "   ███▄", "  █████", "▄██████", "██████ ", " ▀███  ", "  █ █  "] };
    players.forEach(player => {
        if (player.connected) {
            const { dino, ready } = player;
            const frame = dinoArt.idle;
            for (let i = 0; i < frame.length; i++) {
                for (let j = 0; j < frame[i].length; j++) {
                    const charX = Math.floor(dino.x) + j, charY = Math.floor(dino.y) - (frame.length - 1) + i;
                    if (charX >= 0 && charX < GAME_WIDTH && charY >= 0 && charY < GAME_HEIGHT && frame[i][j] !== ' ') {
                        screen[charY][charX] = dino.color + frame[i][j] + colors.reset;
                    }
                }
            }
            const idText = `${dino.id}`;
            const statusText = ready ? `${colors.green}[已准备]${colors.reset}` : `${colors.yellow}[等待中]${colors.reset}`;
            const idY = Math.floor(dino.y) - frame.length - 1;
            if (idY >= 0) screen[idY].splice(Math.floor(dino.x), idText.length, ...idText.split(''));
            
            let currentX = Math.floor(dino.x);
            for (const char of statusText) {
                if (screen[dino.y + 2]) screen[dino.y + 2][currentX] = (screen[dino.y + 2][currentX] || '') + char;
                if (char === '\x1b' || (char > ' ' && screen[dino.y + 2][currentX].includes('\x1b'))) {} else { currentX++; } 
            }
        }
    });
    console.log(screen.map(row => row.join('')).join('\n'));
}

function renderGameWorld() {
    clearScreen();
    const screen = Array.from({ length: GAME_HEIGHT }, () => Array(GAME_WIDTH).fill(' '));
    
    clouds.forEach(cloud => {
        for (let i = 0; i < cloud.art.length; i++) for (let j = 0; j < cloud.art[i].length; j++) {
            const charX = Math.floor(cloud.x) + j, charY = cloud.y + i;
            if (charX >= 0 && charX < GAME_WIDTH && charY >= 0 && charY < GAME_HEIGHT && cloud.art[i][j] !== ' ') {
                screen[charY][charX] = colors.gray + cloud.art[i][j] + colors.reset;
            }
        }
    });

    for (let x = 0; x < GAME_WIDTH; x++) screen[GROUND_Y + 1][x] = colors.gray + ((x + Math.floor(groundOffset)) % 15 === 0 ? '∴' : '▔') + colors.reset;
    
    obstacles.forEach(obstacle => {
        const baseY = obstacle.type.y || GROUND_Y;
        for (let i = 0; i < obstacle.type.draw.length; i++) for (let j = 0; j < obstacle.type.draw[i].length; j++) {
            const charX = Math.floor(obstacle.x) + j, charY = baseY - obstacle.type.draw.length + 1 + i;
            if (charX >= 0 && charX < GAME_WIDTH && charY >= 0 && charY < GAME_HEIGHT && obstacle.type.draw[i][j] !== ' ') {
                screen[charY][charX] = colors.red + obstacle.type.draw[i][j] + colors.reset;
            }
        }
    });
    
    const dinoArt = {
        run1: ["    ▄▄ ", "   ███▄", "  █████", "▄██████", "██████ ", " ▀███  ", "  █ █  "],
        run2: ["    ▄▄ ", "   ███▄", "  █████", "▄██████", "██████ ", " ▀███  ", "   █ █ "],
        jump: ["    ▄▄ ", "   ███▄", "  █████", "▄██████", "██████ ", " ▀███  ", "  ▀ ▀  "]
    };

    players.forEach(player => {
        if (player.connected && player.dino.alive) {
            const { dino } = player;
            const frame = dino.state === DinoState.JUMPING ? dinoArt.jump : (Math.floor(gameDistance / 4) % 2 === 0 ? dinoArt.run1 : dinoArt.run2);
            for (let i = 0; i < frame.length; i++) for (let j = 0; j < frame[i].length; j++) {
                const charX = Math.floor(dino.x) + j, charY = Math.floor(dino.y) - (frame.length - 1) + i;
                if (charX >= 0 && charX < GAME_WIDTH && charY >= 0 && charY < GAME_HEIGHT && frame[i][j] !== ' ') {
                    screen[charY][charX] = dino.color + frame[i][j] + colors.reset;
                }
            }
        }
    });
    
    let scoreText = `${colors.cyan}速度: ${gameSpeed.toFixed(1)} | 距离: ${Math.floor(gameDistance)}${colors.reset}\n`;
    players.forEach(player => {
        if (player.connected) {
            const status = player.dino.alive ? '' : `${colors.gray}(死亡)${colors.reset}`;
            scoreText += `${player.dino.color}${player.dino.id}: ${player.dino.score}${status}  `;
        }
    });
    console.log(scoreText + '\n');
    console.log(screen.map(row => row.join('')).join('\n'));
}

// 键盘监听
function setupKeyboardListeners() {
    // 现在设置RawMode以获取实时按键事件
    if (process.stdin.isTTY) process.stdin.setRawMode(true);
    process.stdin.removeAllListeners('keypress');
    process.stdin.on('keypress', (_, key) => {
        if (key.ctrl && key.name === 'c') process.exit();
        if (gameState === 'waiting' && key.name === 'space') {
            if (isClient) {
                sendToServer({ type: 'ready' });
            } else if (isServer) {
                const serverPlayer = players.get('server');
                if (serverPlayer) {
                    serverPlayer.ready = true;
                    broadcastPlayerList();
                    checkAllReady();
                }
            }
        } else if (gameState === 'playing' && key.name === 'space') {
            const player = players.get(isClient ? currentPlayerId : (gameMode === 'single' ? 'player1' : 'server'));
            if (player) isClient ? sendToServer({ type: 'jump' }) : player.dino.jump();
        } else if (gameState === 'gameover' && key.name === 'r') {
            if (isClient) sendToServer({ type: 'restart' });
            else if (isServer) requestRestart('server');
            else if (gameMode === 'single') startSinglePlayerGame();
        }
    });
}

// 游戏模式选择
function showMenu() {
    clearScreen();
    console.log(`${colors.cyan}${'='.repeat(40)}${colors.reset}`);
    console.log(`${colors.yellow}       恐龙跳跃游戏 - 终端版${colors.reset}`);
    console.log(`${colors.cyan}${'='.repeat(40)}${colors.reset}\n`);
    console.log(`${colors.green}选择游戏模式：${colors.reset}`);
    console.log(`${colors.white}1. 单机模式${colors.reset}`);
    console.log(`${colors.white}2. 创建服务器（联机）${colors.reset}`);
    console.log(`${colors.white}3. 加入服务器（联机）${colors.reset}\n`);
    console.log(`${colors.gray}按对应数字键选择...${colors.reset}`);
    
    process.stdin.once('data', data => {
        const choice = data.toString().trim();
        if (choice === '1') startSinglePlayerGame();
        else if (choice === '2') startServerMode();
        else if (choice === '3') startClientMode();
        else {
            console.log(`${colors.red}无效选择，请重新选择${colors.reset}`);
            setTimeout(showMenu, 1000);
        }
    });
}

// 单机模式
function startSinglePlayerGame() {
    gameMode = 'single';
    players.clear();
    players.set('player1', { dino: new Dino('player1', 10, colors.brightGreen), connected: true, ready: true });
    setupKeyboardListeners();
    startGame();
}

// 服务器模式
function startServerMode() {
    console.log(`${colors.cyan}请输入服务器端口（默认3000）：${colors.reset}`);
    process.stdin.once('data', data => {
        const port = parseInt(data.toString().trim()) || 3000;
        setupKeyboardListeners();
        createServer(port);
        gameState = 'waiting';
        // 服务器端也需要持续渲染
        setInterval(() => {
            if ((gameState === 'playing' || gameState === 'waiting') && isServer) render();
        }, 50);
    });
}

// 客户端模式
function startClientMode() {
    console.log(`${colors.cyan}请输入服务器地址（默认 localhost:3000）：${colors.reset}`);
    process.stdin.once('data', data => {
        const input = data.toString().trim();
        let host = 'localhost', port = 3000;
        if (input) {
            const parts = input.split(':');
            host = parts[0] || 'localhost';
            port = parseInt(parts[1]) || 3000;
        }
        console.log(`${colors.yellow}正在连接到 ${host}:${port}...${colors.reset}`);
        setupKeyboardListeners();
        connectToServer(host, port);
        setInterval(() => {
            if ((gameState === 'playing' || gameState === 'waiting') && isClient) render();
        }, 50);
    });
}

// 程序入口
if (require.main === module) {
    readline.emitKeypressEvents(process.stdin);
    // 先不设置RawMode，在需要时再设置
    process.on('exit', () => {
        if (process.stdin.isTTY) process.stdin.setRawMode(false);
        console.log(`\n${colors.yellow}游戏结束，感谢游玩！${colors.reset}`);
    });
    showMenu();
}